package com.dries.portal.module.circle.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dries.common.api.CommonResult;
import com.dries.portal.module.circle.entity.Circle;
import com.dries.portal.module.circle.entity.CircleLikes;
import com.dries.portal.module.circle.entity.CircleReply;
import com.dries.portal.module.circle.from.AddCircleFrom;
import com.dries.portal.module.circle.mapper.CircleLikesMapper;
import com.dries.portal.module.circle.mapper.CircleMapper;
import com.dries.portal.module.circle.mapper.CircleReplyMapper;
import com.dries.portal.module.circle.service.ICircleService;
import com.dries.portal.module.circle.vo.CircleDetailVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


@Service
public class CircleServiceImpl extends ServiceImpl<CircleMapper, Circle> implements ICircleService {

    @Resource
    private CircleReplyMapper circleReplyMapper;
    @Resource
    private CircleLikesMapper circleLikesMapper;

    @Override
    public CircleDetailVo getCircleDetailById(Integer id) {

        Circle circle = baseMapper.selectById(id);

        if (circle != null) {
            CircleDetailVo detailVo = new CircleDetailVo();
            BeanUtils.copyProperties(circle, detailVo);
            List<CircleReply> circleReplies = circleReplyMapper.selectList(new QueryWrapper<CircleReply>().lambda()
                    .eq(CircleReply::getCircleId, id)
                    .orderByDesc(CircleReply::getCreateTime)
            );

            List<CircleReply> replyList = circleReplies.stream().filter(e -> e.getParentId() == 0)
                    .peek(e -> e.setReplies(getReplies(e, circleReplies))).collect(Collectors.toList());

            detailVo.setReplies(replyList);

            // 更新用户评价浏览量
            Integer pageView = subPageView(detailVo.getId(), detailVo.getCirclePageView() == null ? 0 : detailVo.getCirclePageView());
            detailVo.setCirclePageView(pageView);

            detailVo.setReplies(circleReplies);
            return detailVo;
        }


        return null;
    }

    /**
     * 递归查找所有评价的子评价
     */
    public List<CircleReply> getReplies(CircleReply reply, List<CircleReply> replies){

        return replies.stream().filter(e -> Objects.equals(e.getParentId(), reply.getId()))
                .peek(e -> e.setReplies(getReplies(e, replies))).collect(Collectors.toList());
    }
    /**
     * 用户访问+1
     *
     * @param id
     */
    @Override
    public synchronized Integer subPageView(Integer id, Integer pageView) {
        Circle circle = new Circle();
        circle.setId(id);
        circle.setCirclePageView(++pageView);
        updateById(circle);

        return pageView;
    }

    /**
     * 获取火聚圈动态
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public List<CircleDetailVo> getCircleList(Integer pageNum, Integer pageSize, String userId, Boolean type) {

        List<Circle> circles = new ArrayList<>();
        if (type) {
            // 获取全部列表
            circles = baseMapper.selectList(new QueryWrapper<Circle>().lambda().orderByDesc(Circle::getCreateTime));
        } else {
            // 获取我的动态
            circles = baseMapper.selectList(new QueryWrapper<Circle>().lambda()
                    .eq(Circle::getUserId, userId)
                    .orderByDesc(Circle::getCreateTime));
        }

        // 获取每个列表的动态点赞和评论
        if (CollUtil.isNotEmpty(circles) && circles.size() > 0) {
            return circles.stream().map(e -> {
                List<CircleReply> replies = circleReplyMapper.selectList(new QueryWrapper<CircleReply>().lambda().eq(CircleReply::getCircleId, e.getId()));
                List<CircleLikes> circleLikes = circleLikesMapper.selectList(new QueryWrapper<CircleLikes>().lambda().eq(CircleLikes::getCircleId, e.getId()));
                CircleDetailVo detailVo = buildCircleDetailVo(e);
                for (CircleLikes circleLike : circleLikes) {
                    if (String.valueOf(circleLike.getUserId()).equals(userId)) {
                        detailVo.setIsLike(1);
                    }
                }

                detailVo.setLikes(circleLikes);
                detailVo.setReplies(replies);
                return detailVo;
            }).collect(Collectors.toList());
        }

        return null;
    }

    /**
     * 构造返回前端用户评价的VO对象
     * @return
     */
    private CircleDetailVo buildCircleDetailVo(Circle circle){
        CircleDetailVo detailVo = new CircleDetailVo();
        if (circle.getCircleImgs() != null) {
            detailVo.setCircleImgs(Arrays.asList(circle.getCircleImgs().split(",")));
        }

        BeanUtils.copyProperties(circle, detailVo);
        return detailVo;
    }

    @Override
    public CommonResult saveAddCircleFrom(AddCircleFrom circle) {

        Circle circleDetail = new Circle();

        BeanUtils.copyProperties(circle, circleDetail);
        if (CollUtil.isNotEmpty(circle.getCircleImgs())) {
            circleDetail.setCircleImgs(
                    circle.getCircleImgs().stream()
                            .map(String::toString).collect(Collectors.joining(","))
            );
        }

        int result = baseMapper.insert(circleDetail);
        if (result == 1) {
            return CommonResult.success();
        } else {
            return CommonResult.failed();
        }
    }
}